package com.maysham.coder.server.service.impl;

import com.maysham.coder.server.config.auth.SecurityUtil;
import com.maysham.coder.server.dao.GroupDao;
import com.maysham.coder.server.model.UserGroup;
import com.maysham.coder.server.model.Group;
import com.maysham.coder.server.service.GroupService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl implements GroupService {
    @Resource
    private GroupDao groupDao;

    @Override
    public Group create(Group group) {
        Group group1 = groupDao.create(group);
        UserGroup userGroup = new UserGroup();
        userGroup.setUser(SecurityUtil.current());
        userGroup.setGroup(group1);
        groupDao.addUserGroups(Collections.singleton(userGroup));
        return group1;
    }

    @Override
    public List<Group> queryUserGroups(String userId) {
        List<UserGroup> userGroups = groupDao.findUserGroups(userId);
        if (userGroups == null){
            return null;
        }
        return userGroups.stream().map(UserGroup::getGroup).collect(Collectors.toList());
    }
}
